package com.qf.controller;


import com.github.pagehelper.PageInfo;
import com.qf.constans.ResultCode;
import com.qf.dto.R;
import com.qf.exceptions.AddDataException;
import com.qf.exceptions.QuaryDataException;
import com.qf.exceptions.UpdateException;
import com.qf.mapper.AuthorsMapper;
import com.qf.pojo.Authors;
import com.qf.service.IAuthorsService;
import javafx.beans.DefaultProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/author")
public class AuthorsController {
    private AuthorsMapper authorsMapper;

    public void setAuthorsMapper(AuthorsMapper authorsMapper) {
        this.authorsMapper = authorsMapper;
    }

    private IAuthorsService authorsService;
    @Autowired
    public void setAuthorsService(IAuthorsService authorsService) {
        this.authorsService = authorsService;
    }
    @GetMapping("/author/{authorId}")
    public R findById(@PathVariable Long authorId){
        if(authorId<=0){
            throw new QuaryDataException("错误", ResultCode.FAIL);
        }

        Authors authors = authorsService.find(authorId);

        return R.setOk(authors);
    }
    @GetMapping("/authors/{authorName}/{pageNum}/{pageSize}")
    public R findAllByName(@PathVariable String authorname, @PathVariable int pageNum,@PathVariable  int pageSize){
        System.out.println("模糊查询作者进来了");

        if(authorname==null){
            throw new QuaryDataException("错误", ResultCode.FAIL);
        }
        PageInfo<Authors> allByName = authorsService.findAllByName(authorname, pageNum, pageSize);

        return R.setOk(allByName);
    }

    @PutMapping("/author")
    public R updateAuthor(@RequestBody Authors authors){

        System.out.println("修改作者信息进来了");
        if(authors==null||authors.getAuthorid()<=0){
            throw new UpdateException("修改数据错误", ResultCode.NULL_DATA);
        }

        authorsService.updateAuthors(authors);
        return R.setOk(null);

    }

    @PostMapping("/author")
    public R addAuthors(@RequestBody Authors authors){



        System.out.println("添加作者");
        if(authors==null){
            throw new AddDataException("修改数据错误", ResultCode.NULL_DATA);
        }
        authorsService.addAuthors(authors);
        return R.setOk(null);
    }



}
